﻿using System.Web.Mvc;
using Elmah;
using System.Web;

namespace mBlog.Infrastructure.Filters
{
    public class ElmahHandlerErrorAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            if (HttpContext.Current != null)
                HttpContext.Current.Items["CurrentlyProcessingException"] = true;

            ErrorLog.GetDefault(HttpContext.Current).Log(new Error(context.Exception, HttpContext.Current));

            //BlogConfig blogConfig;
            //using (var session = DocumentStoreHolder.DocumentStore.OpenSession())
            //{
            //    blogConfig = session.Load<BlogConfig>("Blog/Config");
            //}

            var controllerName = (string)context.RouteData.Values["controller"];
            var actionName = (string)context.RouteData.Values["action"];

            var viewResult = new ViewResult
            {
                ViewName = "500",
                ViewData = new ViewDataDictionary(new HandleErrorInfo(context.Exception, controllerName, actionName))
            };

            context.ExceptionHandled = true;
            context.HttpContext.Response.StatusCode = 500;
            context.HttpContext.Response.TrySkipIisCustomErrors = true;
            context.HttpContext.Response.Clear();

            context.Result = viewResult;
        }
    }
}
